package com.guanzhi.HttpRequest;

import com.alibaba.fastjson2.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.util.Strings;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

/**
 * 小工具
 * <p> Package: com.guanzhi.HttpRequest </p>
 * <p> File: HttpRequestUtil.java </p>
 * <p> Description:  (HTTP请求类)</p>
 * <p> Date: 2023/3/22 11:33</p>
 *
 * @author 观之
 * @version 1.0 （代码版本）
 * @email <a href="mailto:guanzhi55634@aliyun.com">观之</a>（邮箱）
 * @since JDK11（JDK版本）
 */
public class HttpRequestUtil {


    /**
     * POST 请求带参(不携带文件流方式)
     *
     * @param url   请求路径
     * @param param 参数 推荐使用转成JSON形式的字符串
     * @return 返回请求结果
     */
    public static JSONObject httpPost(String url, String param) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost method = new HttpPost(url);
        method.setHeader("Content-Type", "application/json");

        // post请求返回结果
        JSONObject jsonResult = new JSONObject();
        try {
            if (Strings.isNotBlank(param)) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(param, "UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            HttpResponse result = httpClient.execute(method);
            //地址加密
            URLDecoder.decode(url, StandardCharsets.UTF_8);
            //请求发送成功，并得到响应
            int statusCode = result.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                String str = EntityUtils.toString(result.getEntity());
                return JSONObject.parseObject(str);
            } else if (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
                jsonResult.put("success", false);
                jsonResult.put("message", "服务器内部错误");
            } else if (statusCode == HttpStatus.SC_NOT_FOUND) {
                jsonResult.put("success", false);
                jsonResult.put("message", "接口没有找到");
            } else {
                jsonResult.put("success", false);
                jsonResult.put("message", "调用出错");
            }
            return jsonResult;

        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            method.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
        return null;
    }
}
